#coding=UTF-8
import os.path
import logging
import logging.handlers

from optparse import OptionParser
from apscheduler.scheduler import Scheduler
import cherrypy

import threading
import json

from nsq.reader import Reader

import config
import urls
import views

version = '1.0.0'

def initLog(options):
    filename = "%s_%s" % (options.logfile, options.port)
    log_path = os.path.dirname(filename)
    if not os.path.isdir(log_path):
        os.makedirs(log_path)
    logger = logging.getLogger()
    hdlr = logging.handlers.TimedRotatingFileHandler(filename, when='midnight', backupCount=options.backupCount)
    formatter = logging.Formatter("[%(asctime)s]: %(module)s %(levelname)s %(message)s ")
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    if options.debug:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

func_conf = {'match_club':{'game_over':views.match_game_over,
                           'room_over':views.match_room_over,
                        },
             }

def consumer(topic='match_club', channel='py'):
    try:
        reader = Reader(topic, channel, nsqd_tcp_addresses=[config.NSQ_ADDR, ])
        for message in reader:
            try:
                #logging.info(message.body)
                msg = json.loads(message.body)
                bid = msg['b']
                uid = msg['u']
                data = msg.get('d',{})
                act = data.get('act')
                if not act:
                    act = 'default'
                topic_handler = func_conf.get(topic, {})
                handler = topic_handler.get(act)
                if not handler:
                    logging.error(u"404 没有对应处理方法,topic:%s,act:%s,msg:%s" % (topic, act, message.body))
                else:
                    logging.info(u"收到消息:topic:%s,uid:%s,data:%s,msg:%s" % (topic, uid, data, message.body))
                    handler(reader, bid, uid, data)
                
            except:
                logging.error("nsq handler error", exc_info=True)
            finally:
                message.fin()
        
    except:
        logging.error("nsq error=================", exc_info=True)
        
def main():
    parser = OptionParser(usage="usage: python %prog [options] filename",
                          version="mserver v%s" % version)
    parser.add_option("-p", "--port",
                      action="store",
                      type="int",
                      dest="port",
                      default=4444,
                      help="Listen Port")
    parser.add_option("-f", "--logfile",
                      action="store",
                      type="string",
                      dest="logfile",
                      default='./logs/run.log',
                      help="LogFile Path and Name. default=./run.log")
    parser.add_option("-n", "--backupCount",
                      action="store",
                      type="int",
                      dest="backupCount",
                      default=10,
                      help="LogFile BackUp Number")
    parser.add_option("-m", "--master",
                      action="store_true",
                      dest="master",
                      default=False,
                      help="master process")
    parser.add_option("-d", "--debug",
                          action="store_true",
                          dest="debug",
                          default=True,
                          help="debug mode")
    (options, args) = parser.parse_args()
    initLog(options)
    
    root = urls.Server()
    root.match = urls.MatchServer()
    #sched = Scheduler()
    #sched.add_cron_job(urls.clear_msg, minute='*/5', second='0')
    #sched.add_cron_job(account.del_cache, minute='*/5', second='0')
    #sched.start()
    threading.Thread(target=consumer, args=('match_club', 'py')).start()
    cherrypy.config.update({'server.socket_host':'0.0.0.0',
                        'server.socket_port':options.port,
                        'server.socket_queue_size':350,
                        'server.max_request_header_size':10 * 1024 * 1024,
                        'server.thread_pool':450,
                        'response.headers.Content-Type': 'application/json; charset=UTF-8',
                        'engine.autoreload.on':False})
    cherrypy.quickstart(root)

if __name__ == '__main__':
    main()
